package net.huashitong.supervision.insideDuCha.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.ObjectUtils;
import net.huashitong.supervision.insideDuCha.dao.InsideCycleDao;
import net.huashitong.supervision.insideDuCha.dto.RemindDto;
import net.huashitong.supervision.insideDuCha.entity.InsideCycleEntity;
import net.huashitong.supervision.insideDuCha.entity.InsideMainTaskEntity;
import net.huashitong.supervision.insideDuCha.entity.InsideSubTaskEntity;
import net.huashitong.supervision.insideDuCha.filter.InsideSubTaskFilter;
import net.huashitong.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class InsideCycleService extends StringPKService<InsideCycleEntity> {

    @Autowired
    private SysTableService tableService;
    @Autowired
    private InsideCycleDao dao;
    @Autowired
    @Lazy
    private InsideMainTaskService mainTaskService;
    @Autowired
    private InsideSubTaskService subTaskService;
    @Autowired
    private InsideUserTaskService userTaskService;
    @Autowired
    private SysUserService userService;

    @Override
    protected BaseDao<InsideCycleEntity, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(InsideCycleEntity obj) {
        obj.setSysId(tableService.updateMaxSysId("inside_cycle_task",null));
    }


    public List<InsideCycleEntity> queryFilterCycle(String taskUserId,String taskSubid,String taskMainId,String userId){
        return dao.getCycles(taskUserId, taskSubid, taskMainId, userId);
    }

    /**
     * 所有有效的的 周期性
     * @return
     */
    public List<InsideCycleEntity> getListCycles()
    {
        List<InsideCycleEntity> cycles = new ArrayList<>();

        String currentDateStr = DateUtil.getCurrentDate();
        Date currentDate = DateUtil.strToDate(currentDateStr);//当前时间
        List<InsideCycleEntity> listCycleRemind = dao.getListCycleRemind();
        for (InsideCycleEntity listCycle : listCycleRemind) {
            String remindDate = listCycle.getRemindDate();
            if(ObjectUtils.isBlank(remindDate))
            {
                continue;
            }
            Date remind = DateUtil.strToDate(remindDate);
            if (remind.compareTo(currentDate)<=0) {
                //
                cycles.add(listCycle);
            }
        }
        return cycles;
    }

    /**
     * 提示事项详情；
     * @param list
     * @return
     */
    public List<RemindDto> getCycleDetailInfos(List<InsideCycleEntity> list){
        List<RemindDto> dtolist = new ArrayList<>();
        for (InsideCycleEntity item : list) {

            String subTaskId = item.getSubTaskId();
            InsideSubTaskEntity subTask = subTaskService.getById(subTaskId);
            InsideMainTaskEntity mainTask = mainTaskService.getById(item.getMainTaskId());

            SysUser user = userService.getById(item.getUserId());
            RemindDto dto = new RemindDto();
            dto.setCycleVale(subTask.getCycleValue());
            dto.setMainTaskId(mainTask.getSysId());
            dto.setMainTaskName(mainTask.getTaskName());
            dto.setSubTaskName(subTask.getSubTaskName());
            dto.setSubTaskId(subTask.getSysId());
            dto.setTimeType(subTask.getTimeType()+"");
            dto.setUserId(item.getUserId());
            dto.setUserName(user.getName());
            dto.setTelphone(user.getMobile());
            dto.setCycleEntityentity(item);
            dtolist.add(dto);

        }

        return dtolist;
    }


    //保存进入提醒信息表

    @Transactional
    public void saveUserCycleRemind(List<InsideSubTaskFilter> subTaskList){

        List<InsideCycleEntity> listCycle = new ArrayList<>();
        for (InsideSubTaskFilter item : subTaskList) {
           // List<String> days = calculateRemindDate(item);
                InsideCycleEntity entity = new InsideCycleEntity();
                entity.setValids(1+"");
                entity.setMainTaskId(item.getTaskMainId());
                entity.setSubTaskId(item.getSysId());
                //entity.setUserTaskId(item.getUserTaskId());
                entity.setUserId(item.getUserId());
                entity.setRemindDate(item.getRemindDate());//提醒日期
                entity.setTimeRound(item.getTimeRound());
                entity.setCycleValue(item.getCycleValue());
                entity.setTimeType(item.getTimeType()+"");
                listCycle.add(entity);
        }

        this. batchSave(listCycle);
    }


    public List<String>  calculateRemindDate(InsideSubTaskFilter userTaskLists){
        List<String>  remindLists = new ArrayList<>();
        int timeType = userTaskLists.getTimeType();
        String remindDate = "";
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        String cycleValue = userTaskLists.getCycleValue();
        switch (timeType){
            case 1:
                //单时限
                remindDate=cycleValue;
                remindLists.add(remindDate);
                break;
            case 2:
                //周期性 天
                int addDay = Integer.parseInt(cycleValue);
                ca.add(Calendar.DATE,addDay);
                remindDate =DateUtil.DateToStr(ca.getTime());
                remindLists.add(remindDate);
                break;
            case 3:
                //周期性 周
                int week = ca.get(Calendar.DAY_OF_WEEK);
                 int wk =Integer.parseInt(cycleValue);
                wk=wk+1;
                int abs = Math.abs(week - wk);
                ca.add(Calendar.DATE,abs);
                remindDate = DateUtil.DateToStr(ca.getTime());
                remindLists.add(remindDate);
                break;
            case 4:
                //周期性 月
                int currDay = ca.get(Calendar.DAY_OF_MONTH);
                int temDay =Integer.parseInt(cycleValue);

                String currentMonth = DateUtil.getCurrentMonth();

                if (currDay-temDay>0) {
                    //提醒日期在  早于 今天，提醒日期设置为下个月的
                    ca.add(Calendar.MONTH,1);
                    ca.getTime();
                    int maximum = ca.getActualMaximum(Calendar.DAY_OF_MONTH);
                    int year = ca.get(Calendar.YEAR);
                    int month =ca.get(Calendar.MONTH)+1;
                    if(maximum-temDay<=0){//考虑2月情况
                        remindDate=year+"-"+month+"-"+maximum;
                    }else {
                        remindDate=year+"-"+month+"-"+temDay;
                    }
                }else {
                    remindDate= currentMonth+"-"+temDay;
                }
                remindLists.add(remindDate);
                break;
            case 5:
                //周期性 季度
                Date alertDate = DateUtil.strToDate(cycleValue);
                Date currDate = DateUtil.strToDate(DateUtil.getCurrentDate());
                if (alertDate.compareTo(currDate)>0) {
                    //提醒日期 是否晚于 今天 如果晚于的话，直接设置。
                    remindDate = cycleValue;
                }else {
                    //下一个季度
                    ca.setTime(alertDate);
                    ca.add(Calendar.MONTH,3);
                    remindDate = DateUtil.DateToStr(ca.getTime());
                }
                remindLists.add(remindDate);
                break;
            case 6:
                //多时限，一次性把所 提醒日期创建好；
                String[] splitDays = cycleValue.split(",");
                for (String str : splitDays) {
                    remindLists.add(str);
                }

                break;

        }
        return  remindLists;
    }

}
